package leetcode.easy.q67;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Q {
    public static void main(String[] args) {
        log.info("{}", new Solution().addBinary("1010", "1011"));
    }
}

/*
转为0/1做二进制和，满二进1
进位+1；

 */
@Slf4j
class Solution {
    public String addBinary(String a, String b) {
        char[] result = new char[Math.max(a.length(), b.length()) + 1];
        int carry = 0, alen = a.length(), blen = b.length(), rlen = result.length;
        for (int i = 0; i < result.length; i++) {
            int ai = alen - i - 1;
            int bi = blen - i - 1;
            int cal = 48;
            if (ai >= 0 && bi >= 0) {
                cal = (a.charAt(ai) + b.charAt(bi)) % 48 + carry;
            } else if (bi >= 0) {
                cal = b.charAt(bi) % 48 + carry;
            } else if (ai >= 0) {
                cal = a.charAt(ai) % 48 + carry;
            } else {
                cal = carry;
            }
            result[rlen - i - 1] = cal % 2 == 1 ? '1' : '0';
            carry = cal / 2;
        }
        return result[0]=='1' ? String.valueOf(result) : String.valueOf(result).substring(1);
    }
}
